package com.libweb.listener;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener// -> web.xml 파일에 listener 등록을 대신하는 annotation
public class LibWebContextListener implements ServletContextListener {

	//web application이 시작될 때 호출되는 메서드
	@Override
	public void contextInitialized(ServletContextEvent arg0) {

		ServletContext application = arg0.getServletContext();
		String path = application.getRealPath("/counter.txt");
		int total = 0;
		File file = new File(path);
		
		if (file.exists()) {
			try {
			BufferedReader breader = new BufferedReader(
				new InputStreamReader(new FileInputStream(file)));
			
			String data = breader.readLine();
			total = Integer.parseInt(data);
			breader.close();
			} catch (Exception ex) {}
		}
		
		application.setAttribute("current", 0);
		application.setAttribute("total", total);
	}
	
	//web application이 종료될 때 호출되는 메서드
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {

		ServletContext application = arg0.getServletContext();
		
		String path = application.getRealPath("/counter.txt");
		
		try {
			PrintStream writer = 
				new PrintStream(new FileOutputStream(path));
			writer.println(application.getAttribute("total"));
			writer.close();		
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}










